package test

import (
	"testing"
	"os"
	"fmt"
	"errors"
	"strconv"
	"io/ioutil"
	"path/filepath"
	"kumachan/standalone/rx"
	"kumachan/interpreter"
	"kumachan/interpreter/runtime/vm"
	"kumachan/interpreter/runtime/lib/env"
)


func getTestDirPath(t *testing.T, kind string) string {
	var exe_path, err = os.Executable()
	if err != nil { t.Fatal(err) }
	var project_path = filepath.Dir(filepath.Dir(exe_path))
	return filepath.Join(project_path, "test", kind)
}

func expectStdIO(t *testing.T, path string, in string, expected_out string) {
	in_read, in_write, e := os.Pipe()
	if e != nil { panic(e) }
	out_read, out_write, e := os.Pipe()
	if e != nil { panic(e) }
	var test_env = env.NewDefaultEnvironment(nil)
	test_env.Stdin = rx.FileFrom(in_read)
	test_env.Stdout = rx.FileFrom(out_write)
	var options = &vm.Options { Environment: test_env }
	go (func() {
		interpreter.Run(path, options, nil)
		var e = out_write.Close()
		if e != nil { panic(e) }
	})()
	_, e = in_write.Write(([] byte)(in))
	if e != nil { panic(e) }
	e = in_write.Close()
	if e != nil { panic(e) }
	out, e := ioutil.ReadAll(out_read)
	if e != nil { panic(e) }
	var actual_out = string(out)
	if actual_out != expected_out {
		t.Fatal(errors.New(fmt.Sprintf(
			"stdout not matching\nexpected result:\n%s\nactual result:\n%s\n",
			strconv.Quote(expected_out), strconv.Quote(actual_out))))
	}
}


